<?php
declare (strict_types=1);

namespace app\common\middleware;

use app\common\model\AdminLog as DataMode;

class Log
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $app = strtolower(app('http')->getName());
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $url = strtolower($request->url());
        if ($request->isAjax() || $request->isPost()) {
            switch ($action) {
                case 'add'://新增
                    $type = 1;
                    break;
                case 'edit'://修改
                case 'update_field'://字段修改
                    $type = 2;
                    break;
                case 'detail'://查看日志
                    $type = !empty(input('id')) ? 3 : '';
                    break;
                case 'login'://登录日志
                    $type = 4;
                    break;
                case 'import_excel'://导入
                    $type = 5;
                    break;
                case 'export_excel'://导出
                    $type = 6;
                    break;
            }
            if (!empty($type) && $controller != 'logc' && $controller != 'storage') {

                $updata = [
                    'id'=>GetSnowID(),
                    'type' => $type,
                    'module' => $app,
                    'controller' => $controller,
                    'action' => $action,
                    'method' => $request->method(),
                    'url' => $url,
                    'post_data' => json_encode($request->post(), JSON_UNESCAPED_UNICODE),
                    'get_data' => json_encode($request->get(), JSON_UNESCAPED_UNICODE),
                    'headers' => json_encode($request->header(), JSON_UNESCAPED_UNICODE),
                    'agent' => $request->server('HTTP_USER_AGENT'),
                    'ip' => $request->ip(),
                    'create_time' => date('Y-m-d H:i:s'),
                    'create_id' => GetToken('id') ?: 0,
                ];
                if ($type == 6) {
                    $ip = GetIpText();
                    $updata['ip_address'] = !empty($ip['address']) ? str_replace(" ", "", $ip['address']) : '内部地址';
                }
                $Model = new DataMode();
                $Model->insert($updata);
            }
        }
        return $next($request);
    }
}